/**
 * 
 */
package com.softwareinlife.xmpp.server.util;

import com.google.appengine.api.xmpp.JID;
import com.softwareinlife.xmpp.server.model.JIDModel;

/**
 * node@domain/resource
 * 
 * @author jangsunjin
 * 
 */
public class JIDUtil {

	/**
	 * Constructor
	 */
	private JIDUtil() {
	}

	/**
	 * Get Node from JID
	 * 
	 * @param JID
	 * @return Node
	 */
	public static String getNode(String JID) {
		JIDModel model = parseJID(JID);

		return model.getNode();
	}

	/**
	 * Get Domain from JID
	 * 
	 * @param JID
	 * @return Domain
	 */
	public static String getDomain(String JID) {
		JIDModel model = parseJID(JID);

		return model.getDomain();
	}

	/**
	 * Get Resource from JID
	 * 
	 * @param JID
	 * @return Resource
	 */
	public static String getResource(String JID) {
		JIDModel model = parseJID(JID);

		return model.getResource();
	}

	/**
	 * node@domain/resource
	 * 
	 * @param JID
	 * @return
	 */
	public static JIDModel parseJID(String JID) {
		if (JID != null && JID.length() > 0) {
			String node = null;
			String domain = null;
			String resource = null;

			String temp[] = JID.split("@");
			if (temp.length == 2) {
				node = temp[0];

				if (temp[1].contains("/")) {
					domain = temp[1].substring(0, temp[1].indexOf("/"));
					resource = temp[1].substring(temp[1].indexOf("/") + 1,
							temp[1].length());
				} else {
					domain = temp[1];
				}

				return new JIDModel(node, domain, resource);
			}
		}

		return null;
	}

	/**
	 * Parse JID
	 * 
	 * @param jid
	 * @return JID Model
	 */
	public static JIDModel parseJID(JID jid) {
		return parseJID(jid.getId());
	}

	/**
	 * Is JID
	 * 
	 * @return
	 */
	public static boolean isJID(String JID) {
		if (JID != null && JID.length() > 0) {
			String temp[] = JID.split("@");
			if (temp.length == 2 && temp[1].contains(".")) {
				return true;
			}
		}

		return false;
	}
}
